import logging
import sys

from PySide6 import QtCore
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QColor, QBrush
from PySide6.QtWidgets import QTreeWidget, QTreeWidgetItem, QMainWindow, QApplication

from exer_lib.utils.log_utils import init_logger

init_logger()
logger = logging.getLogger(__name__)


class CustomTreeWidget(QTreeWidget):
    hovered = Signal(QTreeWidgetItem, QTreeWidgetItem)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.current_item = None

    def mouseMoveEvent(self, event):
        # 获取当前鼠标下的item
        item = self.itemAt(event.position().toPoint())
        if item and item != self.current_item:
            old_item = self.current_item
            self.current_item = item
            self.hovered.emit(old_item, item)
        super().mouseMoveEvent(event)

    def enterEvent(self, event):
        # 当鼠标进入widget时，设置一个默认的hovered item（如果有的话）
        if self.topLevelItemCount() > 0:
            item = self.current_item = self.topLevelItem(0)
            self.hovered.emit(None, item)
        super().enterEvent(event)

    def leaveEvent(self, event, /):
        if self.current_item:
            self.hovered.emit(self.current_item, None)


class MainWindow(QMainWindow):
    def __init__(self):
        logger.debug("__init__ entry")
        super(MainWindow, self).__init__()
        self.tree = CustomTreeWidget(self)
        self.setCentralWidget(self.tree)
        self.tree.setMouseTracking(True)
        self.tree.itemChanged.connect(self.on_item_changed)
        self.tree.hovered.connect(self.on_hovered)
        self.init_tree()
        self.norm_brush = None
        self.highlight_brush = QBrush(QColor("#3574F0"))

    def on_hovered(self, prev: QTreeWidgetItem, curr: QTreeWidgetItem):
        if self.norm_brush is None:
            self.norm_brush = curr.background(0)
        if prev:
            prev.setBackground(0, self.norm_brush)
        if curr:
            curr.setBackground(0, self.highlight_brush)

    def init_tree(self):
        self.tree.setColumnCount(1)
        self.tree.setHeaderLabels(['Name'])
        for i in range(5):
            item = QTreeWidgetItem(self.tree)
            item.setText(0, f'Item {i}')
            item.setData(0, Qt.UserRole, i)
            self.tree.addTopLevelItem(item)
            for j in range(3):  # Add some child items for demonstration
                child = QTreeWidgetItem(item)
                child.setText(0, f'Child {j}')
                child.setData(0, Qt.UserRole, j)
                item.addChild(child)

    def on_item_changed(self, item, column):
        pass


if __name__ == "__main__":
    logger.setLevel(logging.DEBUG)
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
